package server.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import message.GroupChatRequestMessage;
import message.GroupCreateRequestMessage;
import message.GroupCreateResponseMessage;
import server.session.Group;
import server.session.GroupSession;
import server.session.GroupSessionFactory;

import java.util.List;
import java.util.Set;
@ChannelHandler.Sharable
public class GroupCreateRequestMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, GroupCreateRequestMessage groupCreateRequestMessage) throws Exception {
        String groupName = groupCreateRequestMessage.getGroupName();
        Set<String> members = groupCreateRequestMessage.getMembers();
        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        Group group = groupSession.createGroup(groupName, members);
        if (group == null){
//            给创建者发消息
            channelHandlerContext.writeAndFlush(new GroupCreateResponseMessage(true, String.format("创建群%s成功", groupName)));
//            给被拉入群的人发消息
            List<Channel> membersChannel = groupSession.getMembersChannel(groupName);
            membersChannel.stream().forEach(channel -> {
                channel.writeAndFlush(new GroupCreateResponseMessage(true, String.format("你被拉入群%s", groupName)));
            });
        }else {
            channelHandlerContext.writeAndFlush(new GroupCreateResponseMessage(false, String.format("创建群%s失败", groupName)));
        }

    }
}
